package com.guodi.model.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.model.entity.*;
import com.guodi.model.enums.IdtFillTaskScoreEnum;
import com.guodi.model.mapper.IdtFillTaskScoreMapper;
import com.guodi.model.service.IIdtFillTaskScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.model.service.IIdtIndicatorsService;
import com.guodi.model.service.IIdtIndicatorsTypeService;
import com.guodi.model.service.IIdtMonitorValueService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;
import java.util.stream.Collectors;

/**
* 指标填报维度得分表 服务实现类
* @author lzy
* @date 2023-08-03
*/
@Service
public class IdtFillTaskScoreServiceImpl extends ServiceImpl<IdtFillTaskScoreMapper, IdtFillTaskScore> implements IIdtFillTaskScoreService {

    @Resource
    private IdtFillTaskScoreMapper idtFillTaskScoreMapper;

    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;
    @Resource
    private IIdtIndicatorsService iIdtIndicatorsService;
    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;
    @Resource
    private IdtIndicatorsDirServiceImpl idtIndicatorsDirService;


    @Override
    public void calcScoreByYearAndCode(String code, String year, String divisionCode) {
        if(StringUtils.isBlank(code)){
            code = IdtIndicatorsDirServiceImpl.MONITOR_WARNING_CODE;
        }

        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, year, divisionCode);
        if(null == one){
            return ;
        }
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = idtIndicatorsDirService.listDirByCode(one.getId(), null, null);
        if(treeList.size() == 0){
            return ;
        }
        // 过滤出指标
        List<ApiIdtIndicatorsDir> idtList = new ArrayList<>();

        // 获取所有指标
        List<String> idtIdList = new ArrayList<>();

        //所有维度
        List<ApiIdtIndicatorsDir> dirList = new ArrayList<>();

        for(ApiIdtIndicatorsDir dir : treeList){
            if(dir.getType() == 2){
                idtList.add(dir);
                idtIdList.add(dir.getIndicatorsId());
            }
            if(dir.getParentId().equals(one.getId())){
                dirList.add(dir);
            }
        }

        // 查指标数值
        Map<String, List<ApiIndicatorsVal>> idtValMap = iIdtIndicatorsService.mapIdtVal(idtIdList, year, divisionCode, false, false);

        Map<String, ApiIdtIndicatorsDir> idtIndicatorsDirMap = idtList.stream().collect(Collectors.toMap(e -> e.getIndicatorsId(), e -> e, (e1, e2) -> e2));

        List<IdtFillTaskScore> scores = new ArrayList<>();
        //统一时间
        Date now = new Date();
        for(ApiIdtIndicatorsDir dir : dirList){
            IdtFillTaskScore score = new IdtFillTaskScore();
            score.setDivisionCode(divisionCode);
            score.setYear(year);
            score.setType(dir.getIdtName());
            //拼接公式
            List<String> idtIds = idtFillTaskScoreMapper.getChildsIdtId(dir.getId());
            int size = idtIds.size();
            StringBuffer str = new StringBuffer();
            for(String id : idtIds){
                ApiIdtIndicatorsDir indicatorsDir = idtIndicatorsDirMap.get(id);
                if(indicatorsDir != null){
                    List<ApiIndicatorsVal> apiIndicatorsValList = idtValMap.get(id);
                    ApiIndicatorsVal apiIndicatorsVal = apiIndicatorsValList.get(0);
                    //计算评估级别
                    String estimateStatus;
                    if(!StringUtils.isBlank(apiIndicatorsVal.getMonitorValue())){
                        estimateStatus = this.iIdtMonitorValueService.getEstimateStatus(code, id, apiIndicatorsVal.getMonitorValue(), year, divisionCode);
                    }else {
                        estimateStatus = "null,监测值为空";
                    }
                    int num = IdtFillTaskScoreEnum.getScoreByName(estimateStatus);
//                    switch (estimateStatus) {
//                        case "优": num = 100;break;
//                        case "良": num = 80;break;
//                        case "中": num = 70;break;
//                        case "差": num = 50;break;
//                        default: num = 0;break;
//                    }
                    str.append(num).append(" * (1/").append(size).append(")").append(" + ");
                }
            }
            str = str.deleteCharAt(str.length() - 2);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            String result = "";
            try {
                Object object = engine.eval(str.toString());
                result = String.format("%.2f",Double.valueOf(object.toString()));
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            String formula = str.toString().replaceAll(String.valueOf("\\(1/"+size+"\\)"),String.format("%.2f",Double.valueOf(String.valueOf(1D/size * 100))) + "%");
            score.setFormula(formula);
            score.setScore(result);
            score.setType(dir.getName());
            score.setId(UuidUtil.get32UUID());
            score.setCreator(AuthUtil.getUserId().toString());
            score.setCreateTime(now);
            score.setModifier(score.getCreator());
            score.setModifyTime(now);
            scores.add(score);
        }
        this.saveBatch(scores);

    }

    @Override
    public void deleteByYearAndCode(String year, String divisionCode) {
        this.idtFillTaskScoreMapper.deleteByYearAndCode(year,divisionCode);
    }

    @Override
    public IPage<IdtFillTaskScore> listByEntity(Page page, IdtFillTaskScore idtFillTaskScore) {
        IPage<IdtFillTaskScore> iPage = this.idtFillTaskScoreMapper.listByEntity(page,idtFillTaskScore);
        return iPage;
    }

    @Override
    public List<IdtFillTaskScore> lists(IdtFillTaskScore idtFillTaskScore, String ids) {
        List<IdtFillTaskScore> list;
        if(StringUtils.isNotBlank(ids)){
            List<String> idList = Arrays.asList(ids.split(","));
            list = this.idtFillTaskScoreMapper.lists(new IdtFillTaskScore(),idList);
        }else {
            list = this.idtFillTaskScoreMapper.lists(idtFillTaskScore,new ArrayList<>());
        }
        return list;
    }


}
